package com.zhuhjay.service.system.wxmp.strategy.message;

import com.zhuhjay.common.web.enums.MatchingMode;
import com.zhuhjay.common.wxmp.builder.TextBuilder;
import com.zhuhjay.service.system.event.UserOfflineEvent;
import com.zhuhjay.service.system.model.entity.SystemOauth;
import com.zhuhjay.service.system.model.entity.SystemUser;
import com.zhuhjay.service.system.service.SystemOauthService;
import com.zhuhjay.service.system.service.SystemUserService;
import com.zhuhjay.service.system.wxmp.strategy.AbstractMessageStrategy;
import lombok.RequiredArgsConstructor;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import static com.zhuhjay.service.system.enums.OauthTypeEnum.WECHAT;

/**
 * @author ZhuHJay
 * @date 2023/11/12 21:51
 */
@Lazy
@Component
@RequiredArgsConstructor
public class UpdUnameMessage extends AbstractMessageStrategy {

    private final SystemUserService userService;
    private final SystemOauthService oauthService;
    private final ApplicationEventPublisher publisher;

    @Override
    public boolean support(String content) {
        return content.startsWith("用户名");
    }

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, WxMpService wxMpService) {
        String username = wxMessage.getContent().substring(3).trim();
        // 该openid是否绑定账号
        String openid = wxMessage.getFromUser();
        SystemOauth oauth = oauthService.lambdaQuery().eq(SystemOauth::getOpenId, openid).one();
        if (oauth == null) {
            return new TextBuilder().build("您还未绑定账号", wxMessage, wxMpService);
        }
        // 检查该用户是否可以修改用户名
        SystemUser user = userService.getById(oauth.getUserId());
        if (!user.getUsername().startsWith(WECHAT.getType() + '_')) {
            return new TextBuilder().build("您的用户名不是系统生成的，无法修改", wxMessage, wxMpService);
        }
        if (!username.matches(MatchingMode.Username.getRegular())) {
            return new TextBuilder().build("用户名格式不正确", wxMessage, wxMpService);
        }
        if (userService.lambdaQuery().eq(SystemUser::getUsername, username).count() > 0) {
            return new TextBuilder().build("用户名已存在", wxMessage, wxMpService);
        }
        // 修改用户名
        userService.lambdaUpdate()
                .set(SystemUser::getUsername, username)
                .eq(SystemUser::getId, user.getId()).update();
        publisher.publishEvent(new UserOfflineEvent(this, user.getUsername(), null));
        return new TextBuilder().build("用户名修改成功，系统需要重新登录！", wxMessage, wxMpService);
    }

}
